package com.pug.controller.user;

import com.pug.bo.AvatarBo;
import com.pug.bo.BgImgBo;
import com.pug.config.minio.MinIOConfig;
import com.pug.config.minio.MinIoUploadService;
import com.pug.controller.BaseController;
import com.pug.pojo.KssUser;
import com.pug.service.user.UserServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2022/3/16$ 23:56$
 */
@RestController
@RequiredArgsConstructor
public class UserChangeController extends BaseController {
    @Resource
    RabbitTemplate rabbitTemplate;
    private final UserServiceImpl userService;
    @Resource
    MinIoUploadService minIoUploadService;
    @Resource
    MinIOConfig minIOConfig;
    @GetMapping("/getuser/{id}")
    public KssUser getUser(@PathVariable("id")Long id){
        return userService.getById(id);
    }
    //更改头像
    @PostMapping("/user/modifty/avatar/{userId}")
    @Transactional(propagation = Propagation.REQUIRED)
    public AvatarBo changeUserAvatar(@PathVariable("userId") Long userId, @RequestParam("filename") String fileName, MultipartFile file) throws Exception {
        UUID uuid = UUID.randomUUID();
        String s = uuid.toString(); //随机名称
        String oldName=file.getOriginalFilename();
        String exit=oldName.substring(oldName.lastIndexOf('.'));
        minIoUploadService.uploadFile("lqx",s+exit,file.getInputStream());
        String imgUrl = minIOConfig.getFileHost()
                + "/"
                + minIOConfig.getBucketName()
                + "/"
                + s;

        //根据id修改用户的头像
        userService.updateBgImgById(userId,imgUrl+exit);
        return new AvatarBo(imgUrl+exit);
    }
    //更改背景
    @PostMapping("/user/modifty/bgimg/{userId}")
    @Transactional(propagation = Propagation.REQUIRED)
    public BgImgBo changeUserBgImg(@PathVariable("userId")Long userId,String filename,String bucketname,MultipartFile file) throws Exception {
        String s = UUID.randomUUID().toString();//随机背景图片名字
        String exit=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        s=s+exit;
        minIoUploadService.uploadFile("lqx",s,file.getInputStream());
        String imgUrl = minIOConfig.getFileHost()
                + "/"
                + minIOConfig.getBucketName()
                + "/"
                + s;
        userService.updateBgImgById(userId,imgUrl);
        return new BgImgBo(imgUrl);
    }
    //修改用户密码
    @GetMapping("changeUser")
    @Transactional  //开启事务
    public void change(@Param("id")Long id,@Param("password")String password){
        KssUser user = userService.getById(id);
        user.setPassword("abc");
        boolean b = userService.updateById(user);
        if(!b) return;
        IdDto idDto = new IdDto(id);
        //放松mq，保证token被删除
        //向mq发送用户下订单信息，（这是一个死信队列，30分钟用户没有支付，就把用户的订单信息置为-1）
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        // 2: 设置交换机
        rabbitTemplate.setExchange("liu.order.user.exchange_change");
        // 3: 设置路由key
        rabbitTemplate.setRoutingKey("liu.order.user.routing.change");
        // 4: 发送消息，设置消息附属信息，信息载体和消息持久化
        rabbitTemplate.convertAndSend(idDto, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 获取消息属性对象
                MessageProperties messageProperties = message.getMessageProperties();
                // 设置消息的持久化策略
                messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                // 设置消息头的属性的对象
                messageProperties.setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, IdDto.class);
                // 设置额外的参数
                messageProperties.setHeader("msgtype", "1");
                // 返回消息实列
                return message;
            }
        });
    }
}
